package com.htfyun.fbreader;

import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import org.geometerplus.android.fbreader.FBReader;
import org.geometerplus.android.fbreader.NavigationWindow;
import org.geometerplus.fbreader.bookmodel.TOCTree;
import org.geometerplus.fbreader.fbreader.ActionCode;
import org.geometerplus.fbreader.fbreader.FBReaderApp;
import org.geometerplus.zlibrary.core.application.ZLApplication;
import org.geometerplus.zlibrary.text.view.ZLTextView;
import org.geometerplus.zlibrary.text.view.ZLTextWordCursor;
import org.geometerplus.zlibrary.ui.android.R;

import io.apptik.widget.MultiSlider;

/**
 * Created by sst on 2017/11/2.
 */

public class HTFYunMenuPopup extends ZLApplication.PopupPanel{
    public final static String ID = "HTFYunMenuPopup";

    private volatile NavigationWindow myWindow;
    private volatile FBReader myActivity;
    private volatile RelativeLayout myRoot;
    private ZLTextWordCursor myStartPosition;
    private final FBReaderApp myFBReader;
    private volatile boolean myIsInProgress;

    public HTFYunMenuPopup(FBReaderApp fbReader) {
        super(fbReader);
        myFBReader = fbReader;
    }

    public void setPanelInfo(FBReader activity, RelativeLayout root) {
        myActivity = activity;
        myRoot = root;
    }

    public void runMenuPopup() {
        if (myWindow == null || myWindow.getVisibility() == View.GONE) {
            myIsInProgress = false;
            if (myStartPosition == null) {
                myStartPosition = new ZLTextWordCursor(myFBReader.getTextView().getStartCursor());
            }
            Application.showPopup(ID);
        }
    }

    @Override
    protected void show_() {
        if (myActivity != null) {
            createPanel(myActivity, myRoot);
        }
        if (myWindow != null) {
            myWindow.show();
            setupNavigation();
        }
    }

    public void show() {
        show_();
    }

    @Override
    protected void hide_() {
        if (myWindow != null) {
            myWindow.hide();
        }
    }

    @Override
    public String getId() {
        return ID;
    }

    @Override
    protected void update() {
        if (!myIsInProgress && myWindow != null) {
            setupNavigation();
        }
    }

    private void createPanel(final FBReader activity, RelativeLayout root) {
        if (myWindow != null && activity == myWindow.getContext()) {
            return;
        }

        activity.getLayoutInflater().inflate(R.layout.htfyun_menu_panel_bk, root);
        myWindow = (NavigationWindow)root.findViewById(R.id.htfyun_menu_panel);

        final View chapterDetailLayout = myWindow.findViewById(R.id.menuChapterDetailLayout);
        chapterDetailLayout.setVisibility(View.INVISIBLE);
        final ImageView menuUndo = (ImageView) myWindow.findViewById(R.id.menuUndo);
        menuUndo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Animation animation = AnimationUtils.loadAnimation(activity, R.anim.anim_view_click);
                v.startAnimation(animation);


                final ZLTextWordCursor position = myStartPosition;
                myFBReader.getTextView().gotoPosition(position);

                myFBReader.storePosition();

                myStartPosition = null;
                Application.hideActivePopup();
                myFBReader.getViewWidget().reset();
                myFBReader.getViewWidget().repaint();
            }
        });
        final TextView menuTxtChapter = (TextView) myWindow.findViewById(R.id.menuTxtChapter);
        final TextView menuTxtPercent = (TextView) myWindow.findViewById(R.id.menuTxtPercent);
        
        final MultiSlider slider = (MultiSlider)myWindow.findViewById(R.id.menuSlider);
        slider.setOnThumbValueChangeListener(new MultiSlider.OnThumbValueChangeListener() {
            private void gotoPage(int page) {
                final ZLTextView view = myFBReader.getTextView();
                if (page == 1) {
                    view.gotoHome();
                } else {
                    view.gotoPage(page);
                }
                myFBReader.getViewWidget().reset();
                myFBReader.getViewWidget().repaint();
            }
            
            @Override
            public void onValueChanged(MultiSlider multiSlider, MultiSlider.Thumb thumb, int thumbIndex, int value, boolean fromUser) {

                if (fromUser) {
                    final int page = value + 1;
                    final int pagesNumber = multiSlider.getMax() + 1;
                    gotoPage(page);
                    menuTxtPercent.setText(makeProgressText(page, pagesNumber));
                    menuTxtChapter.setText(getTocTitle());

                    if (myStartPosition != null &&
                            !myStartPosition.equals(myFBReader.getTextView().getStartCursor())) {
                        myFBReader.addInvisibleBookmark(myStartPosition);
                        myFBReader.storePosition();
                    }
                    
                }
                
            }
        });
        slider.setOnTrackingChangeListener(new MultiSlider.OnTrackingChangeListener() {
            @Override
            public void onStartTrackingTouch(MultiSlider multiSlider, MultiSlider.Thumb thumb, int value) {
                myIsInProgress = true;
                chapterDetailLayout.setVisibility(View.VISIBLE);
            }

            @Override
            public void onStopTrackingTouch(MultiSlider multiSlider, MultiSlider.Thumb thumb, int value) {
                myIsInProgress = false;
            }
        });

        final View previous = myWindow.findViewById(R.id.menuPrevious);
        final View next = myWindow.findViewById(R.id.menuNext);

        View.OnClickListener listener = new View.OnClickListener() {
            public void onClick(View v) {

                Animation animation = AnimationUtils.loadAnimation(activity, R.anim.anim_view_click);
                v.startAnimation(animation);

                TOCTree toc = null;
                if (v == previous) {

                    toc = myFBReader.getPreviousTOCElement();
                    
                    
                } else if (v == next) {

                    toc = myFBReader.getNextTOCElement();

                }

                if (toc != null) {

                    chapterDetailLayout.setVisibility(View.VISIBLE);

                    final ZLTextView view = myFBReader.getTextView();
                    view.gotoPosition(toc.getReference().ParagraphIndex - 1, 0, 0);

                    myFBReader.getViewWidget().reset();
                    myFBReader.getViewWidget().repaint();
                    
                }
              
            }
        };
        
        previous.setOnClickListener(listener);
        next.setOnClickListener(listener);

        final View menuTxtToc = myWindow.findViewById(R.id.menuTxtToc);
        final View menuTxtPostil = myWindow.findViewById(R.id.menuTxtPostil);
        final View menuTxtSettings = myWindow.findViewById(R.id.menuTxtSettings);
        View.OnClickListener menuTxtListener = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Animation animation = AnimationUtils.loadAnimation(activity, R.anim.anim_view_click);
                v.startAnimation(animation);

                Application.hideActivePopup();

                
                if (v == menuTxtToc) {

                    myFBReader.runAction(ActionCode.SHOW_TOC);

                } else if (v == menuTxtPostil) {

                    myFBReader.runAction(ActionCode.SHOW_POSTIL);

                } else if (v == menuTxtSettings) {

                    myFBReader.runAction(ActionCode.SHOW_PREFERENCES);

                }
                
            }
        };
        menuTxtToc.setOnClickListener(menuTxtListener);
        menuTxtPostil.setOnClickListener(menuTxtListener);
        menuTxtSettings.setOnClickListener(menuTxtListener);
        
        
    }

    private void setupNavigation() {
        final MultiSlider slider = (MultiSlider)myWindow.findViewById(R.id.menuSlider);
        final TextView menuTxtChapter = (TextView) myWindow.findViewById(R.id.menuTxtChapter);
        final TextView menuTxtPercent = (TextView) myWindow.findViewById(R.id.menuTxtPercent);


        final ZLTextView textView = myFBReader.getTextView();
        final ZLTextView.PagePosition pagePosition = textView.pagePosition();

//        int startPage = 0;
//        int endPage = pagePosition.Total;
//        final TOCTree tocElement = myFBReader.getCurrentTOCElement();
//        if (tocElement == null) {
//            return;
//        }
//        final TOCTree nextTocElement = myFBReader.getNextTOCElement();
//        
//        int pageNum = textView.computeTextPageNumberByParagraphIndex(tocElement.getReference().ParagraphIndex);
//
//        if (nextTocElement == null) {
//            if (pagePosition.Total - pageNum > 100) {
//                startPage = pageNum;
//            }
//        } else {
//
//            int nextPageNum = textView.computeTextPageNumberByParagraphIndex(nextTocElement.getReference().ParagraphIndex);
//            if (nextPageNum - pageNum > 100) {
//                startPage = pageNum;
//                endPage = nextPageNum;
//            }
//
//        }
//
//        if (slider.getMin() != (startPage)
//                || slider.getMax() != (endPage - 1)
//                || slider.getProgress() != pagePosition.Current - 1) {
//
//            {
//               //避免 slider 抛异常
//                if (slider.getMax() < startPage) {
//                    slider.setMax(endPage - 1);
//                }
//
//                if (slider.getMin() > (endPage - 1)) {
//                    slider.setMin(startPage);
//                }
//                
//            }
//
//            slider.setMin(startPage);
//            slider.setMax(endPage - 1);
//            slider.setProgress( pagePosition.Current - 1);
//
//            menuTxtChapter.setText(tocElement.getText());
//
//            menuTxtPercent.setText(getPercentBySlider(slider));
//            
//        }

     
        menuTxtChapter.setText(getTocTitle());
        
        if (slider.getMax() != pagePosition.Total - 1 || slider.getProgress() != pagePosition.Current - 1) {
            slider.setMax(pagePosition.Total - 1);
            slider.setProgress(pagePosition.Current - 1);
            menuTxtPercent.setText(makeProgressText(pagePosition.Current, pagePosition.Total));
        }
    }


//    private String getPercentBySlider(MultiSlider slider) {
//
//        final float result = 100.0f * (slider.getProgress() - slider.getMin()) / (slider.getMax() - slider.getMin());
//
//        BigDecimal b = new BigDecimal(result);
//        double f1 = b.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
//
//        return f1 + "%";
//    }

    private String makeProgressText(int page, int pagesNumber) {
        return page + "/" + pagesNumber;
    }

    private String getTocTitle() {
        final TOCTree tocElement = myFBReader.getCurrentTOCElement();
        return tocElement != null ? tocElement.getText() : "";
    }
  

    public final void removeWindow(Activity activity) {
        if (myWindow != null && activity == myWindow.getContext()) {
            final ViewGroup root = (ViewGroup)myWindow.getParent();
            myWindow.hide();
            root.removeView(myWindow);
            myWindow = null;
        }
    }
}
